package com.roc.web.action.agent;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblInsInf;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IorgService;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerinfoStatus;
import com.roc.util.constant.Role;
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/agent")
public class AgentAreaStatisticsAction extends PaginationBaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8948834731290720842L;

	static Logger logger = LogManager.getLogger(AgentAreaStatisticsAction.class);

	private Long psamCardStartNo;
	private Long psamCardEndNo;
	private Long totalNum;
	private AgentAreaStatisticsSearchCondition searchCondition;

	private List<TblInsInf> orgList = new ArrayList<TblInsInf>();

	private InputStream excelFile;
	private String excelName;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	IExcelService excelService;
	
	@Autowired 
	IMerchantServices merchantServices;
	
	@Autowired
	IorgService orgService;
	
	@Autowired
	IPowerInfoService powerInfoService;

	@Action(value = "agentAreaStatisticsInit", results = {
			@Result(name = "success", location = "/pages/agent/agentAreaStatistics.jsp"),
			@Result(name = "error", location = "/error.jsp") }
	)
	public String agentAreaStatisticsInit() throws Exception {
		Operators loginOperator = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);

		if(!loginOperator.getRoleType().equals(Role.AGENT.getCode()) && !loginOperator.getRoleType().equals(Role.SYSTEM.getCode())
				 && !loginOperator.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !loginOperator.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
			addActionError("此登陆账号没有权限");
			return ERROR;
		}
		// 加载数据
		org();

		searchCondition = new AgentAreaStatisticsSearchCondition();
		// 默认查询当天日期
		String today = Constance.currTime();
		searchCondition.setMinDate(today);
		searchCondition.setMaxDate(today);
		
		return SUCCESS;
	}

	@Action(value = "queryAgentAreaStatisticsList", results = { @Result(name = "success", location = "/pages/agent/agentAreaStatistics.jsp") })
	// 查询代理商统计信息
	public String queryAgentAreaStatisticsList() throws Exception {

		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if (searchCondition == null) {
			searchCondition = (AgentAreaStatisticsSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new AgentAreaStatisticsSearchCondition();
			}
		}
		try {

			if(!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())
					 && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();
			
			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());


		//	String sdsybId = Constant.ADMIN_ID;
			String sdsybId = String.valueOf(op.getId());// 当前登录账号id

			String flag = "";
			//如果是风控主管或风控操作员,查询收单事业部下 一级代理商的汇总信息
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
				sdsybId = Constant.SHOUDANSHIYEBU_ID;
			}
			
			if( (null == searchCondition.getAreaCode() || searchCondition.getAreaCode().trim().equals("-1")) // 区域为空
					){
				flag = "1";
			}else if( (null != searchCondition.getAreaCode() && !searchCondition.getAreaCode().trim().equals("-1")) // 区域不为空
					){
				flag = "2";
			}
			
			List<Operators> opBeanList = new ArrayList<Operators>();

			if( null != flag && !flag.equals("") && ( flag.equals("1") || flag.equals("2") ) ){

			    searchCondition.setOp(sdsybId);
			    searchCondition.setRoleType(op.getRoleType());

				// 查询区域信息
			    int rsRows = pagenitionService.countSQL(searchCondition);
				
			    if(rsRows > 0){
				    List<Object> rsList = pagenitionService.findAllSQL(searchCondition,
							calcuStart(getCurrentPage()), rsRows);
				    addRsBeans(rsList, opBeanList);
			    }
			}
			
			searchRsList.clear();
			searchRsList.addAll(opBeanList);
	//		this.setTotalPage(this.calcuTotalPage(opBeanList.size()));
			addActionMessage("当前条件下统计到【"+opBeanList.size()+"】条记录");
	//		getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
	//		getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
	//		getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());

	//		List<Operators> oneAgengList = merchantServices.queryLowOneAgent(searchCondition.getAreaCode());
	//		getRequest().setAttribute("oneAgengList", oneAgengList);
			setSearchToConditionSession(searchCondition);

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}
	
	// 导出excel
	@Action(value = "excelAgentAreaStatisticsList", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xls", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String excelAgentAreaStatisticsList() throws Exception {
		try {
			
			Operators op = (Operators) ActionContext.getContext().getSession().get(Constant.SESSION_LOGIN_MERCHANT);
			
			
			if (searchCondition == null) {
				searchCondition = (AgentAreaStatisticsSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new AgentAreaStatisticsSearchCondition();
				}
			}

			if(!op.getRoleType().equals(Role.AGENT.getCode()) && !op.getRoleType().equals(Role.SYSTEM.getCode())
					 && !op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) && !op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
				addActionError("此登陆账号没有权限");
				return ERROR;
			}
			org();

			// 设置机构号
			List<TblInsInf> orgList= orgService.queryOrgList();
			searchCondition.setOrgCode(orgList.get(0).getInsIdCd());

		//	String sdsybId = Constant.ADMIN_ID;
			String sdsybId = String.valueOf(op.getId());// 当前登录账号id
			
			String flag = "";
			//如果是风控主管或风控操作员,查询收单事业部下 一级代理商的汇总信息
			if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
				sdsybId = Constant.SHOUDANSHIYEBU_ID;
			}

			if( (null == searchCondition.getAreaCode() || searchCondition.getAreaCode().trim().equals("-1")) // 区域为空
					){
				flag = "1";
			}else if( (null != searchCondition.getAreaCode() && !searchCondition.getAreaCode().trim().equals("-1")) // 区域不为空
					){
				flag = "2";
			}
			
			List<Operators> opBeanList = new ArrayList<Operators>();

			if( null != flag && !flag.equals("") && ( flag.equals("1") || flag.equals("2") ) ){

			    searchCondition.setOp(sdsybId);
			    searchCondition.setRoleType(op.getRoleType());
			    
				// 查询区域信息
			    int rsRows = pagenitionService.countSQL(searchCondition);
				
			    if(rsRows > 0){
				    List<Object> rsList = pagenitionService.findAllSQL(searchCondition,
							calcuStart(getCurrentPage()), rsRows);
				    addRsBeans(rsList, opBeanList);
			    }
			}
			
			setExcelName(new String(("审核区域汇总导出-"+ searchCondition.getMinDate() + "-" + searchCondition.getMaxDate() ).getBytes(), "ISO8859-1"));

			HSSFWorkbook work = excelService.statisticsAgentAreaTransQueryExcel(opBeanList,searchCondition.getMinDate(),searchCondition.getMaxDate());
			ByteArrayOutputStream output = new ByteArrayOutputStream();  
			work.write(output);  
			   
			byte[] ba = output.toByteArray();  
			excelFile = new ByteArrayInputStream(ba);  
			output.flush();  
			output.close(); 
		} catch (Exception e) {
			logger.info("######审核汇总导出Excel明细失败######");
			addActionError(e.getMessage());
			return ERROR;
		} 
		return SUCCESS;
	}
	
	public Map<String, Operators> getAreaNameMap(List<Operators> areaList){
		Map<String, Operators> map = new HashMap<String, Operators>();
		
		for (Operators operators : areaList) {
			long key = operators.getId();
			//String value = operators.getRealName();
			map.put(String.valueOf(key), operators);
		}
		return map;
	}




	public void addRsBeans(List<Object> rsList ,List<Operators> opBeanList ){
		if (rsList != null && rsList.size() > 0) {
			
			long count1 = 0l;
			Operators bean = new Operators();
			
			String str = "";
			Iterator iterator = rsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj = (Object[]) iterator.next();
				
				if( (null != str && !str.equals("")) 
						&& !(String.valueOf(obj[0])).equals(str) 
					){
					// 添加前一条数据放入 List
					opBeanList.add(bean);
					
					bean = new Operators();
					count1 = 0l;
				}
				bean.setCompanyName( Constance.Null2EmptyTrim(obj[3]) );
				bean.setRealName( Constance.Null2EmptyTrim(obj[4]) );
				
				// 通过  S_0("01")
				if( null != obj[2] && obj[2].toString().equals(MerinfoStatus.S_0.getCode()) ){
					bean.setCount2(Long.parseLong(obj[1].toString()));
					count1 = count1 + Long.parseLong(obj[1].toString());
				}
				// 驳回  S_4("04")
				if( null != obj[2] && obj[2].toString().equals(MerinfoStatus.S_4.getCode()) ){
					bean.setCount3(Long.parseLong(obj[1].toString()));
					count1 = count1 + Long.parseLong(obj[1].toString());
				}
				// 审核中 S_5("05")
				if( null != obj[2] && obj[2].toString().equals(MerinfoStatus.S_5.getCode()) ){
					bean.setCount4(Long.parseLong(obj[1].toString()));
					count1 = count1 + Long.parseLong(obj[1].toString());
				}
				// 未审核 S_1("00")
				if( null != obj[2] && obj[2].toString().equals(MerinfoStatus.S_1.getCode()) ){
					bean.setCount5(Long.parseLong(obj[1].toString()));
					count1 = count1 + Long.parseLong(obj[1].toString());
				}
				// 总计
				bean.setCount1(count1);
				str = String.valueOf(obj[0]);
			}
			// 添加最后一条数据放入 List
			opBeanList.add(bean);
		}
	}
	// 加载数据
	public void org() throws Exception{
		List<Operators> opList = new ArrayList<Operators>();
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		// 收单事业部Id
	//	String supId = Constant.SHOUDANSHIYEBU_ID;
		String supId = String.valueOf(op.getId());// 当前登录账号id
		
		//如果是风控主管或风控操作员,查询收单事业部下 一级代理商的汇总信息
		if(op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode()) || op.getRoleType().equals(Role.RISK_CONTROL_OPERATORS.getCode())){
			supId = Constant.SHOUDANSHIYEBU_ID;
		}
		// 查询某个代理商的直属代理商
		opList = merchantServices.queryLowOneAgent(supId);
		getRequest().setAttribute("opList", opList);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (AgentStatisticsSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_IMPORT);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_IMPORT,
				searchCondition);
	}

	public Long getPsamCardStartNo() {
		return psamCardStartNo;
	}

	public void setPsamCardStartNo(Long psamCardStartNo) {
		this.psamCardStartNo = psamCardStartNo;
	}

	public Long getPsamCardEndNo() {
		return psamCardEndNo;
	}

	public void setPsamCardEndNo(Long psamCardEndNo) {
		this.psamCardEndNo = psamCardEndNo;
	}

	public Long getTotalNum() {
		return totalNum;
	}

	public void setTotalNum(Long totalNum) {
		this.totalNum = totalNum;
	}

	public List<TblInsInf> getOrgList() {
		return orgList;
	}

	public void setOrgList(List<TblInsInf> orgList) {
		this.orgList = orgList;
	}

	public AgentAreaStatisticsSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(AgentAreaStatisticsSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public String getExcelName() {
		return excelName;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}


}
